package com.stalltea.leetcode.twosum;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yivlchangfa
 * @since 2021/11/25 10:07
 */
public class TwoSum {

    public static int[] twoSum1(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap(16);
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        for (int j = 0; j < nums.length; j++) {
            Integer w = map.get(target - nums[j]);
            if (null != w && j != w) {
                return new int[] { j, w };
            }
        }
        return new int[0];
    }

    public static int[] twoSum12(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap(16);
        for (int i = 0; i < nums.length; i++) {
            // 从已经进入到map的元素中查找
            if (map.containsKey(target - nums[i])) {
                return new int[] { map.get(target - nums[i]), i };
            }
            map.put(nums[i], i);
        }
        return new int[0];
    }

    public static void main(String[] args) {
        int[] array = { 3, 3, 4 };
        System.out.println(Arrays.stream(twoSum1(array, 6)).sum());
    }
}
